package bank.client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import bank.transport.Answer;
import bank.transport.Request;

public class SocketServer {
	private String host;
	private int port;
	private Socket sock;
	private int currentTries = 0;
	private static int MAX_TRIES = 250;
	
	private ObjectOutputStream out;
	private ObjectInputStream in;

	public SocketServer(String host, int port) {
		this.host = host;
		this.port = port;
	}

	private void checkConnection() throws UnknownHostException, IOException {
		if(sock == null || sock.isClosed()) {
			sock = new Socket(host, port);
			out = new ObjectOutputStream(sock.getOutputStream());
			in = new ObjectInputStream(sock.getInputStream());
		}
	}
	
	public synchronized Answer send(Request request) throws UnknownHostException, IOException {
		checkConnection();
		
		out.writeObject(request);
		out.flush();
		
		// Give it MAX_TRIES tries to get an answer. Wait 50ms after each try.
		while(currentTries < MAX_TRIES) {
			currentTries++;
			
			try { 
				Answer answer = (Answer)in.readObject();
				currentTries = 0;
				return answer;
			} catch(ClassNotFoundException e) {
				e.printStackTrace();
				try { Thread.sleep(50); } catch(InterruptedException ex) { }
			}
		}
		currentTries = 0;
		
		// Got no answer from server.
		throw new IOException();
	}
}
